/////////////////////////////// TEMPLATES ///////////////////////////////
var templates = new Array();
var templateImages = new Array();

var fillTemplate = function(data){
	$("#templateName").val(data == undefined ? "":data.name);
	$("#oldTemplateName").val(data == undefined ? "":data.name);
	$("#templateUnit").val(data == undefined ? "":data.unit);
	$("#templateStep").val(data == undefined ? "":data.step);
	$("#templateMinValue").val(data == undefined ? "":data.minValue);
	$("#templateMaxValue").val(data == undefined ? "":data.maxValue);
	$("#templateMinName").val(data == undefined ? "":data.minName);
	$("#templateMaxName").val(data == undefined ? "":data.maxName);
	$("#templateSwitchOnName").val(data == undefined ? "":data.switchOnName);
	$("#templateSwitchOffName").val(data == undefined ? "":data.switchOffName);
	$("#templateIncreaseName").val(data == undefined ? "":data.increaseName);
	$("#templateDecreaseName").val(data == undefined ? "":data.decreaseName);

	$('#templateSubmitter').attr("disabled", false);
	$('#modifyTemplatesResult').html("");
};

function checkTemplate(){
	var templateMinValue = $("#templateMinValue").val();
	var templateMaxValue = $("#templateMaxValue").val();
	var templateStep = $("#templateStep").val();
	var intReg = new RegExp("^[0-9]+$");
	if(!intReg.test(templateMinValue)){
		alert("Please enter a valid integer value for min value!");
		return false;
	}
	if(!intReg.test(templateMaxValue)){
		alert("Please enter a valid integer value for max value!");
		return false;
	}
	if(!intReg.test(templateStep)){
		alert("Please enter a valid integer value for step value!");
		return false;
	}
	return true;
}

var createTemplate = function(){
	fillTemplate();
	$('#templateModifierForm').removeClass('hidden');  // Show main window
	$('#templateModifierFormTitle').html('Create new template');  // Show main window
	$('#templateSubmitter').val('create');
};

var deleteTemplate = function(_templateName){
  $.ajax({
    dataType: 'json',
    url: '/ajax/deleteTemplate',
    data: {name: _templateName},
	beforeSubmit: function() {
		enableRefresh = false;
	},
	success: function(data){
		enableRefresh = true;
		alert(data.message);
		refreshAvailableTemplates();
	},
	error: function(ev) {
	}
  });
};

var refreshAvailableTemplatesHandler = function(data){

	while ($('#AvailableTemplates tbody').children().length > 1) {
		$('#AvailableTemplates tr:nth-child(2)').remove();
	}

	templates = new Array();

	$.each(data, function(index, entry) {
		templates.push(entry);

		var background = '';
		if(index % 2 == 0){
			background = " style='background-color: #ececec;'";
		}
		var row = $('<tr' + background + '>').appendTo('#AvailableTemplates');

		var template = "<img src='images/thumbnails/" + entry.name + "_thumbnail.png' width='20'/>";
		$('<td>')
		.html(template)
		.prependTo(row);
		$('<td>')
		.html(entry.unit)
		.prependTo(row);
		$('<td>')
		.html(entry.maxName)
		.prependTo(row);
		$('<td>')
		.html(entry.maxValue)
		.prependTo(row);
		$('<td>')
		.html(entry.minName)
		.prependTo(row);
		$('<td>')
		.html(entry.minValue)
		.prependTo(row);
		$('<td>')
		.html(entry.name)
		.prependTo(row);
		$("<td width='50px;'>")
		.addClass('action')
		.html('edit')
		.click(function() {
			$('#templateModifierForm').removeClass('hidden');  // Show main window
			$('#templateModifierFormTitle').html('Modify property entry: ' + entry.name);  // Show main window
			$('#templateSubmitter').val('update');
			fillTemplate(entry);
		})
		.appendTo(row);
		$("<td width='50px;'>")
		.addClass('action')
		.html('delete')
		.click(function() {
			deleteTemplate(entry.name);
		})
		.appendTo(row);
	});
	// enableRefresh = true;
	// don't enable it, enable it in refreshAvailableTemplateImagesHandler !!!
};

var refreshAvailableTemplates = function(){
	$.ajax({
		dataType: 'json',
		url: '/ajax/getAvailableTemplates',
		beforeSubmit: function() {
			enableRefresh = false;
		},
		success: refreshAvailableTemplatesHandler,
		error: function(ev) {
		}
	});
};

var refreshAvailableTemplateImagesHandler = function(data){

	while ($('#AvailableTemplateImages tbody').children().length > 1) {
		$('#AvailableTemplateImages tr:nth-child(2)').remove();
	}

	templateImages = new Array();

	$.each(data, function(index, entry) {
		templateImages.push(entry);

		var background = '';
		if(index % 2 == 0){
			background = " style='background-color: #ececec;'";
		}
		var row = $('<tr' + background + '>').appendTo('#AvailableTemplateImages');

		var template = "<img src='images/thumbnails/" + entry.name + "_thumbnail.png' width='20'/>";
		$('<td>')
			.html(entry.filename)
			.prependTo(row);
		$('<td>')
			.html(entry.date)
			.appendTo(row);
		$('<td>')
			.html("&nbsp")
			.appendTo(row);
		$("<td width='50px;'>")
			.addClass('action')
			.html('delete')
			.click(function() {
				deleteTemplateImage(entry.filename);
			})
			.appendTo(row);
	});
	enableRefresh = true;
};

var refreshAvailableTemplateImages = function(){
	$.ajax({
		dataType: 'json',
		url: '/ajax/getTemplateImages',
		beforeSubmit: function() {
			enableRefresh = false;
		},
		success: refreshAvailableTemplateImagesHandler,
		error: function(ev) {
		}
	});
};

$(document).ready(function() {
	$('#templateModifier').ajaxForm({
		dataType: 'json',
		beforeSubmit: function() {
			var everythingIsOk = checkTemplate();
			if(everythingIsOk){
				enableRefresh = false;
				$('#templateSubmitter').attr("disabled", true);
			}
			else
				return false;
		},
		success: function(data){
			var $out = $('#modifyTemplateResult');

			$out.removeClass('errorMsg');
			$out.removeClass('warnMsg');
			if(data.status = 'WARN'){
				$out.addClass('warnMsg');
			} else if(data.status = 'ERROR'){
				$out.addClass('errorMsg');
			}

			$out.append(data.message);
			refreshAvailableTemplates();
			enablerefresh = true;
		}
	});
});
/////////////////////////////// TEMPLATES END ///////////////////////////////
